﻿/**
* userCtrl - AngularJS module for right sidebar.
*
*
* Credits
* =======
*
* Copyright 2015 LonghronShen <LonghronShen@Hotmail.com>
*/
(function () {
    "use strict";

    /**
     * Config
     */
    var moduleName = 'app';
    var DEFAULT_ID = '__default';

    /**
     * Module
     */
    var module;
    try {
        module = angular.module(moduleName);
    } catch (err) {
        // named module does not exist, so create one
        module = angular.module(moduleName, []);
    }

    module.controller('userCtrl', ['$scope','$filter', '$rootScope', '$state', '$ngBootbox', 'dataService', 'valueservice', 'uiGridConstants', function ($scope,$filter, $rootScope, $state, $ngBootbox, dataService, valueservice, uiGridConstants) {
        // console.info("<userCtrl> Defining userCtrl...");
        window.localStorage.id = null;
        window.localStorage.carCode = null;

        $scope.searchingKeyword = "";
        //$scope.searchingRoleId = "";
        $scope.searchingCarcode = "";
        $scope.searchingDriverName = "";
        $scope.searchingPhoneNumber = "";
        $scope.searchingApplicationStartTime = "";
        $scope.searchingApplicationEndTime = "";
        $scope.searchingState = '2';
        $scope.searchingEnableState = 0;
        $scope.searchingStartTime = "";
        $scope.searchingEndTime = '';

        var orderBy = $scope.orderBy = "";
        var acs = $scope.acs = 0;
        var skip = $scope.skip = 0;
        var count = $scope.count = 10;
        
        //角色
        $scope.roles = [];
        var str = [];

        //审核状态枚举
        $scope.checkState = valueservice.getRealNameState().slice(1);
        $scope.selectedUser = {};
        //初始化列表
        var loadUsers = function (keyword,realName,phoneNumber, carCode, startTime, endTime,applicationStartTime,applicationEndTime,isEnabled, state, useCache, orderBy,acs,skip, count) {
            dataService.getUsers(keyword, realName, phoneNumber, carCode, startTime, endTime, applicationStartTime, applicationEndTime, isEnabled, state, useCache == null ? false : useCache, orderBy, acs,skip, count).then(function (res) {
                res = res.data || { Response: { Output: { List: [], Total: 0 } } };
                res = res || { output: { list: [], total: 0 } };
                res.output = res.output || { list: [], total: 0 };
                // console.info("loadUsers: getUsers returned: ", res);
                var list = res.output.list;
                // console.info("loadUsers: list: ", list);
                for (var i = 0; i < list.length; i++) {
                    list[i].Id = i + 1 + skip;
                    list[i].RealNameState = valueservice.getRealNameState()[list[i].realNameState].text;
                    //list[i].roles = translateRealRoles(list[i].Roles);
                    list[i].isLockedout = list[i].isLockedout;
                    list[i].IsLockedout = (list[i].isLockedout == true) ? '是' : ((list[i].isLockedout == false) ? '否' : '');
                    list[i].CarLength = valueservice.getCarLength()[list[i].carLength].text;
                    list[i].CarType = valueservice.getCarType()[list[i].carType].text;
                    // list[i].CertificationApplicationTime = $filter('date')(list[i].certificationApplicationTime, 'yyyy-MM-dd HH:mm:ss');
                    // list[i].CertificationApplicationTime = list[i].certificationApplicationTime.replace(/T/, " ").replace(/Z/, "");
                    // list[i].CertificationTime = $filter('date')(list[i].certificationTime, 'yyyy-MM-dd HH:mm:ss');
                    // list[i].CertificationTime = list[i].certificationTime.replace(/T/, " ").replace(/Z/, "");
                }
                //$scope.gridApi.grid.options.totalItems = res.result.total;
                $scope.gridApi.grid.options.totalItems = res.output.total;
               
                // console.info("loadUsers: list test1: ", list);
                $scope.userList = { data: list };
                var currentPage = $scope.gridApi.grid.options.paginationCurrentPage;
                var totalPages = $scope.gridApi.pagination.getTotalPages();
                if (totalPages < currentPage) { $scope.gridApi.grid.options.paginationCurrentPage = 1; };
                $scope.seeks = false;
            }, function (rej) {
                $ngBootbox.alert(rej);
                $scope.seeks = false;
            });
        };

        //分页初始化
        var paginationOptions = {
            pageNumber: 0,
            pageSize: 10,
            currentPage: 1,
            sort: null,
            useCache: true
        };
        var _userList = $scope.userList = {
            data: [],
            paginationPageSizes: [10, 20, 30],
            useExternalPagination: true,
            useExternalSorting: true,
            enableColumnResizing: true,
            columnDefs: [
                { displayName: "序号", field: 'Id', enableColumnMenu: false, enableSorting: false},
                {
                    displayName: "手机号码", field: 'phoneNumber', enableColumnMenu: false, cellTooltip:
                true, headerTooltip: true, enableSorting: true
                },
                { displayName: "车牌号", field: 'carNumber', enableColumnMenu: false ,enableSorting: false},
                { displayName: "司机姓名", field: 'realName', enableColumnMenu: false ,enableSorting: false},
                { displayName: "车型", field: 'CarType', enableColumnMenu: false ,enableSorting: false},
                { displayName: "车长", field: 'CarLength', enableColumnMenu: false ,enableSorting: false},
                //{ displayName: "用户名", field: 'UserName', enableColumnMenu: false },
                { displayName: '申请认证时间', field: 'certificationApplicationTime',type:'date',cellFilter: 'date:"yyyy-MM-dd HH:mm:ss"', enableColumnMenu: false,width: '10%' },
                { displayName: '认证通过时间', field: 'certificationTime', type:'date',cellFilter: 'date:"yyyy-MM-dd HH:mm:ss"',enableColumnMenu: false,width: '10%' },
                { displayName: '认证状态', field: 'RealNameState', enableColumnMenu: false, enableSorting: false},
                { displayName: '禁用状态', field: 'IsLockedout', enableColumnMenu: false, enableSorting: false},
                //{ displayName: '角色', field: 'roles', enableColumnMenu: false },
                {
                    displayName: "操作",
                    field: '操作',
                    cellFilter: 'checkmark',
                    // cellTemplate: '../../../tpl/app_management_user_table_cell.html',
                    cellTemplate:'<a data-toggle="modal" class="fa fa-edit m-l-xs primary text-info" title="编辑" ng-click="grid.appScope.linkToAccountInfo(row.entity)"></a> <a class="fa fa-check-circle primary text-success" ng-click="grid.appScope.disabledStar(row.entity.userId)" title="启用" ng-show="row.entity.isLockedout"></a>  <a class="fa fa-minus-circle primary text-primary" ng-hide="row.entity.isLockedout" title="禁用" ng-click="grid.appScope.disableUser(row.entity.userId)"></a>',
                    enableColumnMenu: false,
                    enableSorting: false
                }
            ],
            onRegisterApi: function (gridApi) {
                $scope.gridApi = gridApi;
                $scope.gridApi.core.on.sortChanged($scope, $scope.sortChanged);
                $scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.OPTIONS);
                gridApi.pagination.on.paginationChanged($scope, function (newPage, pageSize) {
                    paginationOptions.pageNumber = newPage * pageSize - pageSize;
                    paginationOptions.pageSize = pageSize;
                    paginationOptions.currentPage = newPage;
                    $scope.gridApi.grid.options.paginationCurrentPage = newPage;
                    $scope.skip = paginationOptions.pageNumber;
                    $scope.count = paginationOptions.pageSize;
                    loadUsers($scope.searchingKeyword,$scope.searchingDriverName,$scope.searchingPhoneNumber,$scope.searchingCarcode,$scope.searchingStartTime,$scope.searchingEndTime,$scope.searchingApplicationStartTime,$scope.searchingApplicationEndTime,$scope.searchingEnableState,$scope.searchingState,
                         paginationOptions.useCache, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                    paginationOptions.useCache = true;
                });
            }
        };
        //排序
        $scope.sortChanged = function (grid, sortColumns) {
            if (sortColumns.length === 0) {
                loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
            } else {
                switch (sortColumns[0].sort.direction) {
                    case "asc":
                        // $scope.orderBy = sortColumns[0].name;
                        $scope.orderBy = sortFun(sortColumns[0].name);
                        $scope.acs = 2;
                        loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                        break;
                    case "desc":
                        // $scope.orderBy = sortColumns[0].name;
                        $scope.orderBy = sortFun(sortColumns[0].name);
                        $scope.acs = 1;
                        loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                        break;
                    case undefined:
                        loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);
                        break;
                }
            };
        };
        function sortFun(name){
            switch(name){
                case'carNumber':
                return 'Code';
                case'CarType':return 'Type';
                case'CarLength':return 'Length';
                case'RealNameState':return 'CertificationStatus';
                case'IsLockedout':return 'LockoutEnabled';
                default:return name;
            }
        }
        loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            true, $scope.orderBy, $scope.acs, paginationOptions.pageNumber, paginationOptions.pageSize);

        $scope.seeks = true;
        //查询调用
        $scope.queryUsers = function () {
            $scope.seeks = true;
            paginationOptions.pageNumber = 0;
            paginationOptions.currentPage = 1;
            paginationOptions.useCache = false;
            loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, '', 0, paginationOptions.pageNumber, paginationOptions.pageSize);
        };
        //角色
        //dataService.getUserRoles().then(function (res) {

        //    // console.info("getUserRoles returned: ", res.data.Response.UserRoles);
        //    for (var m = 0; m < res.data.Response.UserRoles.length; m++) {
        //        var StrElement = { 'Id': res.data.Response.UserRoles[m].Id, 'Name': res.data.Response.UserRoles[m].Name, 'chineseName': translateRolesEngligh(res.data.Response.UserRoles[m].Name) };
        //        str.push(StrElement);
        //    }
        //    // console.info('str',str);
        //    $scope.roles = str;
        //}, function (rej) {
        //    $ngBootbox.alert(rej);
        //});

        ////角色转换
        //function translateRoles(id) {
        //    // console.info("$scope.roles1 ", $scope.roles);
        //    var UserRole = $scope.roles;
        //    for (var z = 0; z < UserRole.length; z++) {
        //        if (id == UserRole[z].Id) {
        //            return UserRole[z].chineseName;
        //        }
        //    }
        //}
        //function translateRealRoles(roleList) {
        //    // console.info('role list', roleList);
        //    for (var j = 0; j < roleList.length; j++) {
        //        var name = translateRoles(roleList[j]) + ' ';
        //        return name;
        //    }
        //};
        //end角色转换
        

        //启用
        $scope.disabledStar = function (userId) {
            $ngBootbox.confirm('是否启用该权限').then(function () {
                dataService.setAccountLockoutState(userId, false).then(function (res) {
                    paginationOptions.useCache = false;
                    //$scope.gridApi.pagination.raise.paginationChanged(paginationOptions.currentPage, paginationOptions.pageSize);
                    loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, '', 0, paginationOptions.pageNumber, paginationOptions.pageSize);
                }, function (rej) {
                    $ngBootbox.alert(rej)
                });
            }, function () {
                return;
            });
        }
        //禁用
        $scope.disableUser = function (userId) {
            $ngBootbox.confirm('是否禁用该用户').then(function () {
                dataService.setAccountLockoutState(userId, true).then(function (res) {
                    paginationOptions.useCache = false;
                    //$scope.gridApi.pagination.raise.paginationChanged(paginationOptions.currentPage, paginationOptions.pageSize);
                    loadUsers($scope.searchingKeyword, $scope.searchingDriverName, $scope.searchingPhoneNumber, $scope.searchingCarcode, $scope.searchingStartTime, $scope.searchingEndTime, $scope.searchingApplicationStartTime, $scope.searchingApplicationEndTime, $scope.searchingEnableState, $scope.searchingState,
            false, '', 0, paginationOptions.pageNumber, paginationOptions.pageSize);
                }, function (rej) { $ngBootbox.alert(rej); })
            }, function () {
                return;
            });
        };
        
        //跳转到账户信息
        $scope.linkToAccountInfo = function (user) {
            $state.go("app.management.account_info", { id: user.userId, carNumber: user.carNumber });
        }

    }]);
})();